<template>
  <div>
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10">添加日报</Button>
      <Button
        type="primary"
        :loading="refreshLoading"
        @click="refreshEvent"
        shape="circle"
        icon="md-refresh"
        class="fr"
      ></Button>
      <Select v-model="searchTypeValue" class="searchInputClass">
        <Option v-for="item in searchType" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
      <Input
        v-model="searchKeyWord"
        placeholder="请输入搜索关键字"
        :type="searchInputType"
        suffix="ios-search"
        class="searchKeyWordInputClass"
      />
    </Card>
    <!--表格start-->
    <Card>
      <Tables
        ref="tables"
        editable
        v-model="searchData"
        :columns="columns"
        :loading="loading"
        :border="true"
        size="large"
      />
    </Card>
    <!--表格end-->

    <!--分页start-->
    <Page
      :total="num"
      @on-change="changePage"
      show-sizer
      show-elevator
      show-total
      :page-size="pageSize"
      :page-size-opts="$store.state.pageSizeArray"
      @on-page-size-change="changePageSize"
      style="margin-top: 12px; float: right"
    />
    <!--分页end-->

    <!--添加数据模态框start-->
    <Modal
      title="添加数据"
      v-model="addModal"
      :styles="{ top: '50px',width:'60%' }"
      @on-ok="addDataEventOk"
    >
      <Form :model="addData" :label-width="80" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="addData.date" type="date" class="inputWidth200" placeholder="请选择日期."></Input>
        </FormItem>
        <FormItem label="商品：" prop="type">
          <Radio-group v-model="addData.type" type="button" size="large">
            <Radio v-for="value in paperType" :key="value" :label="value"></Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="标题：" prop="title">
          <Input
            v-model="addData.title"
            maxlength="50"
            type="text"
            placeholder="请输入标题，字数在1-50位之间。"
          />
        </FormItem>
        <FormItem label="内容：">
          <Input
            v-model="addData.content"
            maxlength="500"
            show-word-limit
            type="textarea"
            placeholder="请输入内容，字数在1-500位之间."
            :rows="10"
          />
        </FormItem>
      </Form>
    </Modal>
    <!--添加数据模态框end-->

    <Modal
      title="修改数据"
      v-model="editModal"
      :styles="{ top: '50px',width:'60%'  }"
      @on-ok="editDataEvent"
      @on-cancel="editDataEventCancel"
    >
      <Form :model="editData" :label-width="80" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="editData.date" type="date" class="inputWidth200" placeholder="请选择日期."></Input>
        </FormItem>
        <FormItem label="商品：" prop="type">
          <Radio-group v-model="editData.type" type="button" size="large">
            <Radio v-for="value in paperType" :key="value" :label="value"></Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="标题：" prop="title">
          <Input
            v-model="editData.title"
            maxlength="50"
            type="text"
            placeholder="请输入标题，字数在1-50位之间。"
          />
        </FormItem>
        <FormItem label="内容：">
          <Input
            v-model="editData.content"
            maxlength="500"
            show-word-limit
            type="textarea"
            placeholder="请输入内容，字数在1-500位之间."
            :rows="10"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import expandRow from "_c/tables/config-expand.vue";
import {
  getDailyPaper,
  addDailypaperData,
  deleteDailypaperData,
  editDailypaperData
} from "@/api/content/luggage/dailypaper";
export default {
  components: {
    Tables,
    expandRow
  },
  data() {
    return {
      paperType: ["日报", "周报"],
      ruleValidate: {
        date: [
          {
            required: true,
            message: "您未选择日期或格式不正确，请重新选择.",
            trigger: "blur"
          }
        ],
        title: [
          {
            required: true,
            message: "您输入的标题不能为空，字数在1-50位之间，请重新输入.",
            trigger: "blur"
          }
        ],
        type: [
          {
            required: true,
            message: "您未选择类型或格式不正确，请重新选择.",
            trigger: "blur"
          }
        ],
        content: [
          {
            required: true,
            message: "您输入的内容不能为空，字数在1-500位之间，请重新输入.",
            trigger: "blur"
          }
        ]
      },
      refreshLoading: false,
      num: 0,
      //表格列
      columns: [
        {
          title: "日期",
          key: "date",
          width: 150,
          align: "center",
          sortable: true
        },
        {
          title: "类型",
          key: "type",
          width: 100,
          align: "center",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h("span", params.row.type == 0 ? "日报" : "周报")
            ]);
          }
        },
        {
          title: "标题",
          key: "title",
          width: 250,
          align: "center",
          sortable: true
        },
        {
          title: "更多",
          type: "expand",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row
              }
            });
          }
        },
        {
          title: "内容",
          key: "content",
          align: "center",
          ellipsis: true
        },

        {
          title: "操作",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.editData.type =
                        this.editData.type == 0 ? "日报" : "周报";
                      this.showEditModal();
                    }
                  }
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?"
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除.");
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning"
                      },
                      style: {
                        marginRight: "5px"
                      }
                    },
                    "删除"
                  )
                ]
              )
            ]);
          }
        }
      ],
      //搜索类型
      searchType: [
        {
          label: "日期",
          value: "date"
        },
        {
          label: "标题",
          value: "title"
        },
        {
          label: "类型",
          value: "type"
        },
        {
          label: "内容",
          value: "content"
        }
      ],
      //搜索类型值
      searchTypeValue: "date",
      //搜索关键字
      searchKeyWord: "",
      searchInputType: "date",
      tableData: [],
      //分页
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      //添加数据
      addData: { date: "", type: "日报", title: "", content: "" },
      //添加数据模态框状态
      addModal: false,
      //修改数据
      editData: {},
      //修改数据模态框状态
      editModal: false
    };
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter(item => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    }
  },
  methods: {
    //添加数据
    addDataEventOk(e) {
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        this.addData.type = this.addData.type == "日报" ? 0 : 1;
        addDailypaperData(this.addData)
          .then(res => {
            if (res.data.code == 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.addData.type = this.addData.type == 0 ? "日报" : "周报";
              this.addData.title = "";
              this.addData.content = "";
              this.$Message.success("您成功添加了一条数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您添加数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch(err => {
            this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    editDataEventCancel() {
      this.getData(this.pageCurrent, this.pageSize);
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //删除数据
    deleteDataEvent(row) {
      deleteDailypaperData(row.id)
        .then(res => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一条数据.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您删除数据失败了，错误原因：" + res.data.msg);
          }
        })
        .catch(err => {
          this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //修改数据
    editDataEvent() {
      if (!this.requireFormData(this.editData)) {
        this.getData(this.pageCurrent, this.pageSize);
        return;
      } else {
        this.editData.type = this.editData.type === "日报" ? 0 : 1;
        editDailypaperData(this.editData)
          .then(res => {
            if (res.data.code === 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.$Message.success("您成功修改了一条数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch(err => {
            this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },

    //查询数据
    getData(page, pageNum) {
      this.loading = true;
      getDailyPaper(page, pageNum)
        .then(res => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            this.loading = false;
            this.refreshLoading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch(err => {
          this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    //打开添加模态框
    showAddModal() {
      this.addModal = true;
    },

    //打开修改模态框
    showEditModal() {
      this.editModal = true;
    },

    //分页数据
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示数据
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    },
    requireFormData(data) {
      if (data.title.length <= 0 || data.title.length > 50) {
        this.$Message.warning("您输入的标题应在1-50字之间，请重新输入.");
        return false;
      } else if (data.content.length <= 0 || data.content.length > 500) {
        this.$Message.warning("您输入的内容应在1-500字之间，请重新输入.");
        return false;
      } else if (data.date.length != 10) {
        this.$Message.warning("您输入的日期格式错误，请重新输入.");
        return false;
      } else if (data.mode < 0) {
        this.$Message.warning("您未选择支付方式或格式错误，请选择支付方式.");
        return false;
      } else {
        return true;
      }
    },
    formatDate() {
      let nowDate = new Date();
      let y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = nowDate.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    }
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.page, this.pageSize);
  },
  watch: {
    searchTypeValue(value) {
      this.searchInputType = value == "date" ? "date" : "text";
    }
  },
  mounted() {
    this.addData.date = this.formatDate();
  }
};
</script>